/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FileSendFrame.java
 *
 * Created on 2011-11-6, 10:10:50
 */

package com.lanchat.view;

import com.lanchat.model.data.ChatMessage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author GM
 */
public class FileSendFrame extends javax.swing.JFrame implements Runnable{

    private File file;
    private String ip;
    private String filename;
    private int length;
    private int port;
    /** Creates new form FileSendFrame */
    public FileSendFrame() {
        initComponents();
        this.setVisible(true);
    }

    public FileSendFrame(String IP,File f){
        initComponents();
        this.setVisible(true);
        file=f;
        ip=IP;
        filename=f.getName();
        length=(int)f.length();
        Progress.setMaximum(length);
        FName.setText("文件名："+filename);
        MainListFrame.fileSend.put(ip, this);
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        FName = new javax.swing.JLabel();
        Progress = new javax.swing.JProgressBar();
        StartButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        FName.setText("文件名：");

        StartButton.setText("开始");
        StartButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                StartButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(StartButton)
                    .addComponent(Progress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(FName))
                .addContainerGap(51, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addComponent(FName)
                .addGap(18, 18, 18)
                .addComponent(Progress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(StartButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void StartButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_StartButtonActionPerformed
        // TODO add your handling code here:
        ChatMessage cm=new ChatMessage(this.filename+"#"+this.length, MainListFrame.localUser.getUserName(),
                MainListFrame.localUser.getAddress(), ChatMessage.FILE_SEND);
        MainListFrame.send.send(cm, ip);
        StartButton.setEnabled(false);
    }//GEN-LAST:event_StartButtonActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        // TODO add your handling code here:
        MainListFrame.fileSend.remove(ip);
    }//GEN-LAST:event_formWindowClosed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:
        MainListFrame.fileSend.remove(ip);
    }//GEN-LAST:event_formWindowClosing

    /**
    * @param args the command line arguments
    */

    @Override
    public void run() {
        try {
            Socket socket = new Socket(ip, port);
            BufferedOutputStream out=new BufferedOutputStream(socket.getOutputStream());
            FileInputStream fin=new FileInputStream(file);

            int ch;
            while((ch=fin.read())!=-1){
                out.write(ch);
                Progress.setValue(Progress.getValue()+1);
            }
            fin.close();
            out.close();
            socket.close();
            JOptionPane.showMessageDialog(null, "发送成功！");
            this.dispose();
        } catch (UnknownHostException ex) {
            Logger.getLogger(FileSendFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(FileSendFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void SetPort(int port){
        this.port=port;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel FName;
    private javax.swing.JProgressBar Progress;
    private javax.swing.JButton StartButton;
    // End of variables declaration//GEN-END:variables

}
